#include "GameServer.h"
#include <QDataStream>
#include <QDebug>
#include <QDateTime>
#include <QThread>

// 静态调试开关定义 - 修改这里控制服务端调试信息
bool GameServer::s_debugMode = true;  // 设为true开启调试，false关闭调试

// 调试输出宏 - 只在调试模式开启时输出
#define DEBUG_LOG(msg) do { if (GameServer::s_debugMode) qDebug() << msg; } while(0)

// GameServer 实现
GameServer::GameServer(QObject* parent)
    : QObject(parent)
    , m_receiver(nullptr)
    , m_workerThread(nullptr)
    , m_worker(nullptr)
    , m_isRunning(false)
    , m_port(0)
    , m_nextPlayerId(1000)
{
    qDebug() << "MUD游戏服务器创建完成";
}

GameServer::~GameServer()
{
    stopServer();
    qDebug() << "MUD游戏服务器已销毁";
}

bool GameServer::startServer(quint16 port) 
{
    if (m_isRunning) 
    {
        qWarning() << "服务器已在运行";
        return false;
    }
    
    // 创建UDP接收器
    m_receiver = new QUdpSocket(this);
    if (!m_receiver->bind(QHostAddress::Any, port)) 
    {
        qCritical() << "无法绑定端口" << port << ":" << m_receiver->errorString();
        delete m_receiver;
        m_receiver = nullptr;
        return false;
    }
    
    // 创建工作线程
    m_workerThread = new QThread(this);
    m_worker = new NetworkWorker();
    m_worker->moveToThread(m_workerThread);
    
    // 连接信号
    connect(m_receiver, &QUdpSocket::readyRead, this, &GameServer::onReceiveMessageEvent);
    connect(m_worker, &NetworkWorker::packetProcessed, this, &GameServer::onPacketProcessed);
    connect(m_worker, &NetworkWorker::universalMessageProcessed, this, &GameServer::onUniversalMessageProcessed);
    
    // 启动工作线程
    m_workerThread->start();
    
    m_port = port;
    m_isRunning = true;
    
    qDebug() << QString("*** MUD游戏服务器启动成功:");
    qDebug() << QString("    监听端口: %1").arg(port);
    qDebug() << QString("    工作线程: 已启动");
    qDebug() << QString("    服务器状态: 运行中");
    qDebug() << QString("等待勇士们的挑战...");
    
    return true;
}

void GameServer::stopServer() 
{
    if (!m_isRunning) 
    {
        return;
    }
    
    qDebug() << "*** 正在停止MUD游戏服务器...";
    
    m_isRunning = false;
    
    // 停止所有战斗计时器
    QMutexLocker timerLocker(&m_timersMutex);
    for (auto timer : m_combatTimers) 
    {
        if (timer) 
        {
            timer->stop();
            timer->deleteLater();
        }
    }
    m_combatTimers.clear();
    timerLocker.unlock();
    
    // 关闭套接字
    if (m_receiver) 
    {
        m_receiver->close();
        delete m_receiver;
        m_receiver = nullptr;
    }
    
    // 停止工作线程
    if (m_workerThread) 
    {
        m_workerThread->quit();
        m_workerThread->wait(5000);
        if (m_worker) 
        {
            delete m_worker;
            m_worker = nullptr;
        }
        delete m_workerThread;
        m_workerThread = nullptr;
    }
    
    // 清理玩家
    m_players.clear();
    
    qDebug() << "MUD游戏服务器已完全停止";
}

void GameServer::onReceiveMessageEvent() 
{
    while (m_receiver && m_receiver->hasPendingDatagrams()) 
    {
        QByteArray datagram;
        datagram.resize(static_cast<int>(m_receiver->pendingDatagramSize()));
        
        QHostAddress sender;
        quint16 senderPort;
        
        qint64 size = m_receiver->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        
        if (size > 0) 
        {
            datagram.resize(static_cast<int>(size));
            
            // 将数据包发送到工作线程处理
            QMetaObject::invokeMethod(m_worker, "processPacket", Qt::QueuedConnection,
                                    Q_ARG(QByteArray, datagram),
                                    Q_ARG(QHostAddress, sender),
                                    Q_ARG(quint16, senderPort));
        }
    }
}

void GameServer::onPacketProcessed(std::shared_ptr<GamePacket> packet, const QHostAddress& sender, quint16 port) 
{
    if (!packet) 
    {
        return;
    }
    
    qDebug() << QString("收到数据包: %1 (ID:%2)").arg(static_cast<int>(packet->type)).arg(packet->playerId);
    
    // 根据数据包类型分发处理
    switch (packet->type) 
    {
        case PacketType::PLAYER_JOIN:
            handlePlayerJoin(packet, sender, port);
            break;
        case PacketType::PLAYER_LEAVE:
            handlePlayerLeave(packet, sender, port);
            break;
        case PacketType::GAME_START:
            handleGameStart(packet, sender, port);
            break;
        case PacketType::ATTACK:
            handleAttack(packet, sender, port);
            break;
        default:
            qDebug() << "未处理的数据包类型:" << static_cast<int>(packet->type);
            break;
    }
}

void GameServer::handlePlayerJoin(std::shared_ptr<GamePacket> packet, const QHostAddress& sender, quint16 port) 
{
    quint32 playerId = generatePlayerId();
    QString playerName = QString("勇士_%1").arg(playerId);
    
    qDebug() << QString("=== 新玩家加入 ===");
    qDebug() << QString("玩家ID: %1").arg(playerId);
    qDebug() << QString("玩家名称: %1").arg(playerName);
    qDebug() << QString("来源地址: %1:%2").arg(sender.toString()).arg(port);
    
    addPlayer(playerId, playerName, sender, port);
    
    // 发送加入确认
    auto response = std::make_shared<GamePacket>(PacketType::PLAYER_JOIN, playerId);
    sendRawData(response->serialize(), sender, port);
    
    qDebug() << QString("已向玩家 %1 发送加入确认").arg(playerName);
    
    // 延迟发送欢迎信息和初始状态
    QTimer::singleShot(500, [this, playerId, playerName]() {
        // 发送欢迎信息
        sendCombatMessage(playerId, "");
        sendCombatMessage(playerId, "🎉🎉🎉 欢迎来到MUD冒险世界！ 🎉🎉🎉");
        sendCombatMessage(playerId, "===========================================");
        sendCombatMessage(playerId, QString("👋 你好，%1！").arg(playerName));
        sendCombatMessage(playerId, "");
        sendCombatMessage(playerId, "👤 【你的初始属性】");
        sendCombatMessage(playerId, "   💪 等级: 1");
        sendCombatMessage(playerId, "   ❤️  血量: 100/100");
        sendCombatMessage(playerId, "   ⚔️  攻击力: 1");
        sendCombatMessage(playerId, "   🏆 总击杀: 0");
        sendCombatMessage(playerId, "");
        sendCombatMessage(playerId, "🎯 【游戏说明】");
        sendCombatMessage(playerId, "   • 输入 /start 开始第一关冒险");
        sendCombatMessage(playerId, "   • 输入 /attack 开始自动战斗");
        sendCombatMessage(playerId, "   • 输入 /status 查看详细状态");
        sendCombatMessage(playerId, "   • 输入 /help 查看所有指令");
        sendCombatMessage(playerId, "");
        sendCombatMessage(playerId, "💡 准备好了吗？输入 /start 开始你的冒险之旅！");
        sendCombatMessage(playerId, "===========================================");
    });
}

void GameServer::handlePlayerLeave(std::shared_ptr<GamePacket> packet, const QHostAddress& sender, quint16 port) 
{
    qDebug() << QString(">>> 收到主动离开指令 - 玩家ID: %1").arg(packet->playerId);
    
    QMutexLocker locker(&m_playersMutex);
    if (m_players.contains(packet->playerId)) 
    {
        QString playerName = m_players[packet->playerId].playerName;
        qDebug() << QString("    玩家: %1 主动请求离开游戏").arg(playerName);
        locker.unlock();
        
        removePlayer(packet->playerId, true);
        
        // 发送离开确认
        auto response = std::make_shared<GamePacket>(PacketType::PLAYER_LEAVE, packet->playerId);
        sendRawData(response->serialize(), sender, port);
        
        qDebug() << QString("已确认玩家 %1 的离开请求").arg(playerName);
    }
}

void GameServer::handleGameStart(std::shared_ptr<GamePacket> packet, const QHostAddress& sender, quint16 port) 
{
    qDebug() << QString(">>> 收到游戏开始指令 - 玩家ID: %1").arg(packet->playerId);
    qDebug() << QString("发送者地址: %1:%2").arg(sender.toString()).arg(port);
    qDebug() << QString("当前时间: %1").arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
    
    QMutexLocker locker(&m_playersMutex);
    qDebug() << QString("互斥锁获取成功，开始查找玩家ID: %1").arg(packet->playerId);
    qDebug() << QString("当前玩家列表大小: %1").arg(m_players.size());
    
    if (m_players.contains(packet->playerId)) 
    {
        PlayerInfo& player = m_players[packet->playerId];
        QString playerName = player.playerName;
        
        qDebug() << QString("    玩家: %1 请求开始游戏").arg(playerName);
        qDebug() << QString("    当前玩家状态 - level:%1, gameState:%2, isInAutoCombat:%3")
                   .arg(player.gameData.level)
                   .arg(static_cast<int>(player.gameData.gameState))
                   .arg(player.gameData.isInAutoCombat);
        
        // 🔄 检查是否需要重新开局（如果玩家已经在游戏中）
        bool isRestart = (player.gameData.gameState == GameState::IN_COMBAT || 
                         player.gameData.level > 1 || 
                         player.gameData.totalKills > 0);
        
        qDebug() << QString("是否重新开局: %1").arg(isRestart);
        
        if (isRestart) {
            qDebug() << QString("    检测到重新开局请求，重置玩家 %1 的游戏数据").arg(playerName);
            
            // 重置玩家游戏数据到初始状态
            player.gameData = PlayerGameData();
            player.currentMonster = MonsterData();
            
            // 释放玩家锁后再停止自动战斗，避免死锁
            locker.unlock();
            
            qDebug() << "调用stopAutoCombat";
            stopAutoCombat(packet->playerId);
            qDebug() << "stopAutoCombat完成";
            qDebug() << "开始发送重新开局确认消息";
            sendCombatMessage(packet->playerId, "🔄 =======================================");
            sendCombatMessage(packet->playerId, "🔄 重新开局确认！游戏数据已重置");
            sendCombatMessage(packet->playerId, "🔄 =======================================");
            sendCombatMessage(packet->playerId, "📡 正在准备全新的游戏数据...");
            qDebug() << "重新开局确认消息发送完成";
        } else {
            // 普通的开始游戏
            locker.unlock();
            qDebug() << "开始发送普通开始游戏消息";
            sendCombatMessage(packet->playerId, "🎮 服务器收到开始游戏指令！");
            sendCombatMessage(packet->playerId, "📡 正在准备游戏数据...");
            qDebug() << "普通开始游戏消息发送完成";
        }
        
        // 根据是否为重新开局决定后续操作
        if (isRestart) {
            // 重新开局：只重置数据，回到等待状态，不立即开始新游戏
            qDebug() << "重新开局完成，发送等待状态给客户端";
            
            // 重新加锁获取玩家数据
            QMutexLocker restartLocker(&m_playersMutex);
            if (m_players.contains(packet->playerId)) {
                PlayerInfo& restartPlayer = m_players[packet->playerId];
                restartPlayer.gameData.gameState = GameState::WAITING; // 确保状态为等待中
                
                // 发送游戏状态数据包给客户端，让客户端显示等待状态
                auto statusPacket = std::make_shared<GameStatusPacket>(packet->playerId, 
                                                                      restartPlayer.gameData, 
                                                                      restartPlayer.currentMonster, 
                                                                      "🔄 重新开局完成！准备开始新的冒险吧！");
                restartLocker.unlock();
                sendToPlayer(packet->playerId, statusPacket);
                
                sendCombatMessage(packet->playerId, "");
                sendCombatMessage(packet->playerId, "🎮 重新开局完成！");
                sendCombatMessage(packet->playerId, "💡 点击 '🎮 开始游戏' 按钮开始新的冒险！");
                sendCombatMessage(packet->playerId, "");
                
                qDebug() << "重新开局状态发送完成";
            }
        } else {
            // 普通开始游戏：调用完整的游戏开始逻辑
            qDebug() << "准备调用startNewGame";
            startNewGame(packet->playerId);
            qDebug() << "startNewGame调用完成";
        }
    } 
    else 
    {
        qDebug() << QString("    错误: 玩家ID %1 不存在").arg(packet->playerId);
        qDebug() << "当前玩家列表内容:";
        for (auto it = m_players.begin(); it != m_players.end(); ++it) {
            qDebug() << QString("  - 玩家ID: %1, 名称: %2").arg(it.key()).arg(it.value().playerName);
        }
    }
    qDebug() << "handleGameStart方法执行完成";
}

void GameServer::handleAttack(std::shared_ptr<GamePacket> packet, const QHostAddress& sender, quint16 port) 
{
    QMutexLocker locker(&m_playersMutex);
    if (m_players.contains(packet->playerId)) 
    {
        PlayerInfo& player = m_players[packet->playerId];
        
        qDebug() << QString(">>> 收到攻击指令 - 玩家: %1").arg(player.playerName);
        
        if (player.gameData.gameState == GameState::IN_COMBAT) 
        {
            if (player.gameData.isInAutoCombat) 
        {
            locker.unlock();
                sendCombatMessage(packet->playerId, "战斗已经在进行中，请等待战斗结束！");
                return;
            }
            
            locker.unlock();
            startAutoCombat(packet->playerId);
        } 
        else 
        {
            locker.unlock();
            sendGameStatus(packet->playerId, "你当前不在战斗状态！请先输入 /start 开始游戏");
        }
    }
}

// 游戏逻辑实现
void GameServer::startNewGame(quint32 playerId) 
{
    DEBUG_LOG("startNewGame被调用，玩家ID：" << playerId);
    
    // 停止之前的自动战斗（如果有的话）
    stopAutoCombat(playerId);
    
    QMutexLocker locker(&m_playersMutex);
    if (!m_players.contains(playerId)) 
    {
        DEBUG_LOG("startNewGame: 玩家不存在" << playerId);
        return;
    }
    
    PlayerInfo& player = m_players[playerId];
    
    // 设置游戏状态为战斗中
    player.gameData.gameState = GameState::IN_COMBAT;
    player.gameData.isInAutoCombat = false; // 还没开始自动战斗
    
    DEBUG_LOG("准备生成新怪物");
    
    // 生成怪物（注意：不要在这里使用QMutexLocker，因为上面已经锁定了）
    generateNewMonster(playerId);
    
    // 获取生成的怪物和玩家数据
    MonsterData currentMonster = player.currentMonster;
    PlayerGameData currentPlayer = player.gameData;
    QString playerName = player.playerName;
    
    locker.unlock();
    
    DEBUG_LOG("开始发送游戏状态信息");
    
    // 发送游戏开始信息
    sendCombatMessage(playerId, QString(""));
    sendCombatMessage(playerId, QString("🎮 ======================================="));
    sendCombatMessage(playerId, QString("🆕 第 %1 关开始！").arg(currentPlayer.level));
    sendCombatMessage(playerId, QString("🎮 ======================================="));
    sendCombatMessage(playerId, QString(""));
    
    // 显示玩家完整属性（包含防御和暴击）
    sendCombatMessage(playerId, QString("👤 玩家状态 [%1]:").arg(playerName));
    sendCombatMessage(playerId, QString("   ❤️ 血量: %1/%2").arg(currentPlayer.health).arg(currentPlayer.maxHealth));
    sendCombatMessage(playerId, QString("   ⚔️ 攻击力: %1").arg(currentPlayer.attackPower));
    sendCombatMessage(playerId, QString("   🛡️ 防御力: %1").arg(currentPlayer.defense));
    sendCombatMessage(playerId, QString("   ⚡ 暴击率: %1°").arg(currentPlayer.critChance));
    sendCombatMessage(playerId, QString("   💥 暴击倍数: %1x").arg(QString::number(currentPlayer.critMultiplier, 'f', 1)));
    sendCombatMessage(playerId, QString("   🎯 命中率: %1°").arg(currentPlayer.hitChance));
    sendCombatMessage(playerId, QString("   💨 闪避率: %1°").arg(currentPlayer.dodgeChance));
    sendCombatMessage(playerId, QString("   🏆 总击杀: %1").arg(currentPlayer.totalKills));
    sendCombatMessage(playerId, QString(""));
    
    // 显示怪物完整属性（包含防御和暴击）
    sendCombatMessage(playerId, QString("👹 对手信息:"));
    sendCombatMessage(playerId, QString("   📛 名称: %1").arg(currentMonster.name));
    sendCombatMessage(playerId, QString("   ❤️ 血量: %1/%2").arg(currentMonster.health).arg(currentMonster.maxHealth));
    sendCombatMessage(playerId, QString("   ⚔️ 攻击力: %1").arg(currentMonster.attackPower));
    sendCombatMessage(playerId, QString("   🛡️ 防御力: %1").arg(currentMonster.defense));
    sendCombatMessage(playerId, QString("   ⚡ 暴击率: %1°").arg(currentMonster.critChance));
    sendCombatMessage(playerId, QString("   💥 暴击倍数: %1x").arg(QString::number(currentMonster.critMultiplier, 'f', 1)));
    sendCombatMessage(playerId, QString("   🎯 命中率: %1°").arg(currentMonster.hitChance));
    sendCombatMessage(playerId, QString("   💨 闪避率: %1°").arg(currentMonster.dodgeChance));
    sendCombatMessage(playerId, QString(""));
    
    // 根据关卡类型显示特殊提示
    if (currentPlayer.level == 10 || currentPlayer.level == 20 || currentPlayer.level == 30) {
        sendCombatMessage(playerId, QString("🏆 ======================================="));
        if (currentPlayer.level == 10) {
            sendCombatMessage(playerId, QString("🥇 这是第一阶段Boss关！"));
        } else if (currentPlayer.level == 20) {
            sendCombatMessage(playerId, QString("🥈 这是第二阶段Boss关！"));
        } else if (currentPlayer.level == 30) {
            sendCombatMessage(playerId, QString("👑 这是最终Boss关！"));
        }
        sendCombatMessage(playerId, QString("🎁 击败Boss可获得丰厚奖励！"));
        sendCombatMessage(playerId, QString("🏆 ======================================="));
    } else if (currentPlayer.level <= 9) {
        sendCombatMessage(playerId, QString("🟢 威胁等级：⭐ 初级"));
    } else if (currentPlayer.level <= 19) {
        sendCombatMessage(playerId, QString("🟡 威胁等级：⭐⭐ 中级"));
    } else if (currentPlayer.level <= 29) {
        sendCombatMessage(playerId, QString("🔴 威胁等级：⭐⭐⭐ 高级"));
    }
    
    sendCombatMessage(playerId, QString(""));
    sendCombatMessage(playerId, QString("💡 输入 /attack 开始自动战斗！"));
    
    DEBUG_LOG("游戏状态信息发送完成");
    
    // 🔥 关键修复：发送GAME_STATUS数据包，让客户端更新游戏状态和UI
    DEBUG_LOG("发送GAME_STATUS数据包给客户端");
    sendGameStatus(playerId, "游戏准备完成，可以开始战斗！");
    DEBUG_LOG("GAME_STATUS数据包发送完成");
}

void GameServer::generateNewMonster(quint32 playerId) 
{
    // 注意：此方法假设调用者已经持有m_playersMutex锁
    if (!m_players.contains(playerId)) 
    {
        DEBUG_LOG("generateNewMonster: 玩家不存在" << playerId);
        return;
    }
    
    PlayerInfo& player = m_players[playerId];
    player.currentMonster = MonsterData(player.gameData.level, player.gameData.attackPower);
    
    DEBUG_LOG(QString("为玩家 %1 生成怪物: %2").arg(player.playerName).arg(player.currentMonster.name));
}

void GameServer::processAttack(quint32 playerId) 
{
    // 这个方法现在由startAutoCombat替代，保留空实现以兼容
    startAutoCombat(playerId);
}

void GameServer::sendGameStatus(quint32 playerId, const QString& message) 
{
    QMutexLocker locker(&m_playersMutex);
    if (!m_players.contains(playerId)) 
    {
        return;
    }
    
    const PlayerInfo& player = m_players[playerId];
    auto statusPacket = std::make_shared<GameStatusPacket>(playerId, player.gameData, player.currentMonster, message);
    
    locker.unlock();
    
    sendToPlayer(playerId, statusPacket);
}

// 玩家管理
void GameServer::addPlayer(quint32 playerId, const QString& name, const QHostAddress& address, quint16 port) 
{
    QMutexLocker locker(&m_playersMutex);
    m_players[playerId] = PlayerInfo(playerId, name, address, port);
}

void GameServer::removePlayer(quint32 playerId, bool isVoluntary) 
{
    // 停止该玩家的战斗计时器
    stopAutoCombat(playerId);
    
    QMutexLocker locker(&m_playersMutex);
    QString clientKey;
    if (m_players.contains(playerId)) 
    {
        PlayerInfo& player = m_players[playerId];
        QString playerName = player.playerName;
        clientKey = QString("%1:%2").arg(player.address.toString()).arg(player.port);
        
        qDebug() << QString("玩家 %1 离开游戏 (%2)").arg(playerName).arg(isVoluntary ? "主动" : "超时");
        
        m_players.remove(playerId);
    }
    locker.unlock();
    
    // 清理客户端类型映射
    if (!clientKey.isEmpty()) {
        QMutexLocker clientTypesLocker(&m_clientTypesMutex);
        m_clientTypes.remove(playerId);
        m_addressToClientType.remove(clientKey);
    }
    
    // 清理计时器
    QMutexLocker timerLocker(&m_timersMutex);
    if (m_combatTimers.contains(playerId)) 
    {
        QTimer* timer = m_combatTimers[playerId];
        if (timer) 
        {
            timer->deleteLater();
        }
        m_combatTimers.remove(playerId);
    }
}

PlayerInfo* GameServer::getPlayer(quint32 playerId) 
{
    QMutexLocker locker(&m_playersMutex);
    if (m_players.contains(playerId)) 
    {
        return &m_players[playerId];
    }
    return nullptr;
}

QList<PlayerInfo> GameServer::getAllPlayers() const 
{
    QMutexLocker locker(const_cast<QMutex*>(&m_playersMutex));
    return m_players.values();
}

void GameServer::sendToPlayer(quint32 playerId, std::shared_ptr<GamePacket> packet) 
{
    DEBUG_LOG(QString("sendToPlayer开始 - 玩家ID: %1").arg(playerId));
    DEBUG_LOG("准备获取m_playersMutex锁");
    
    QMutexLocker locker(&m_playersMutex);
    DEBUG_LOG("m_playersMutex锁获取成功");
    
    if (m_players.contains(playerId)) 
    {
        DEBUG_LOG("找到玩家，准备发送数据");
        const auto& player = m_players[playerId];
        DEBUG_LOG(QString("准备序列化数据包，类型: %1").arg(static_cast<int>(packet->type)));
        QByteArray data = packet->serialize();
        DEBUG_LOG(QString("数据包序列化完成，大小: %1 字节").arg(data.size()));
        DEBUG_LOG("准备调用sendRawData");
        sendRawData(data, player.address, player.port);
        DEBUG_LOG("sendRawData调用完成");
    } 
    else 
    {
        DEBUG_LOG(QString("玩家ID %1 不存在").arg(playerId));
    }
    
    DEBUG_LOG("sendToPlayer完成");
}

void GameServer::sendRawData(const QByteArray& data, const QHostAddress& target, quint16 port) 
{
    if (m_receiver) 
    {
        m_receiver->writeDatagram(data, target, port);
    }
}

quint32 GameServer::generatePlayerId() 
{
    return m_nextPlayerId++;
} 

// 新增：自动战斗系统实现
void GameServer::startAutoCombat(quint32 playerId) 
{
    QMutexLocker locker(&m_playersMutex);
    if (!m_players.contains(playerId)) 
    {
        qDebug() << "startAutoCombat: 玩家不存在" << playerId;
        return;
    }
    
    PlayerInfo& player = m_players[playerId];
    player.gameData.isInAutoCombat = true;
    locker.unlock();
    
    qDebug() << QString("*** 开始自动战斗: 玩家 %1 VS %2").arg(player.playerName).arg(player.currentMonster.name);
    
    // 发送详细的战斗开始信息
    sendCombatMessage(playerId, "===========================================");
    sendCombatMessage(playerId, QString("⚔️ 自动战斗开始！你 VS %1").arg(player.currentMonster.name));
    sendCombatMessage(playerId, "===========================================");
    
    // 等待一秒后发送状态信息
    QTimer::singleShot(500, [this, playerId]() {
        QMutexLocker statusLocker(&m_playersMutex);
        if (!m_players.contains(playerId)) return;
        
        PlayerInfo& player = m_players[playerId];
        statusLocker.unlock();
        
        sendCombatMessage(playerId, QString("👤 你的状态: 生命 %1/%2，攻击力 %3")
                         .arg(player.gameData.health).arg(player.gameData.maxHealth).arg(player.gameData.attackPower));
        sendCombatMessage(playerId, QString("👹 %1 的状态: 生命 %2/%3，攻击力 %4")
                         .arg(player.currentMonster.name).arg(player.currentMonster.health)
                         .arg(player.currentMonster.maxHealth).arg(player.currentMonster.attackPower));
        sendCombatMessage(playerId, "-------------------------------------------");
        sendCombatMessage(playerId, "战斗即将开始，准备第一轮攻击...");
    });
    
    // 启动战斗计时器，延迟1.5秒开始第一轮，然后每3秒一个回合
    QTimer* combatTimer = getCombatTimer(playerId);
    if (combatTimer) 
    {
        combatTimer->stop();
        // 第一次攻击延迟1.5秒
        QTimer::singleShot(1500, [this, playerId, combatTimer]() {
            if (combatTimer) {
                combatTimer->start(3000); // 3秒一个回合，给用户更多时间看消息
                processCombatRound(playerId); // 立即执行第一轮
            }
        });
    }
}

void GameServer::stopAutoCombat(quint32 playerId) 
{
    QMutexLocker locker(&m_playersMutex);
    if (m_players.contains(playerId)) 
    {
        m_players[playerId].gameData.isInAutoCombat = false;
    }
    locker.unlock();
    
    QMutexLocker timerLocker(&m_timersMutex);
    if (m_combatTimers.contains(playerId)) 
    {
        QTimer* timer = m_combatTimers[playerId];
        if (timer) 
        {
            timer->stop();
        }
    }
}

void GameServer::processCombatRound(quint32 playerId) 
{
    DEBUG_LOG("=== processCombatRound开始 - 玩家" << playerId << "===");
    
    // 先复制所有需要的数据，然后立即释放锁
    QString playerName;
    QString monsterName;
    quint32 playerAttack, playerDefense, playerCritChance;
    double playerCritMultiplier;
    quint32 playerHealth, playerMaxHealth;
    quint32 monsterHealth, monsterMaxHealth;
    quint32 monsterAttack, monsterDefense, monsterCritChance;
    double monsterCritMultiplier;
    bool isPlayerInCombat = false;
    bool isMonsterAlive = false;
    
    // 战斗结果
    PlayerGameData::AttackResult playerAttackResult;
    bool playerAttackHit = false;
    quint32 actualDamage = 0;
    
    {
        QMutexLocker locker(&m_playersMutex);
        if (!m_players.contains(playerId)) 
        {
            DEBUG_LOG("processCombatRound: 玩家不存在" << playerId);
            return;
        }
        
        DEBUG_LOG("找到玩家，开始处理战斗回合");
        
        PlayerInfo& player = m_players[playerId];
        MonsterData& monster = player.currentMonster;
        
        if (!player.gameData.isInAutoCombat || player.gameData.gameState != GameState::IN_COMBAT) 
        {
            DEBUG_LOG(QString("processCombatRound: 战斗状态异常 - isInAutoCombat:%1, gameState:%2")
                        .arg(player.gameData.isInAutoCombat).arg(static_cast<int>(player.gameData.gameState)));
            return;
        }
        
        DEBUG_LOG("战斗状态正常，继续处理");
        
        // 复制玩家数据
        playerName = player.playerName;
        playerAttack = player.gameData.attackPower;
        playerDefense = player.gameData.defense;
        playerCritChance = player.gameData.critChance;
        playerCritMultiplier = player.gameData.critMultiplier;
        playerHealth = player.gameData.health;
        playerMaxHealth = player.gameData.maxHealth;
        
        // 复制怪物数据
        monsterName = monster.name;
        monsterHealth = monster.health;
        monsterMaxHealth = monster.maxHealth;
        monsterAttack = monster.attackPower;
        monsterDefense = monster.defense;
        monsterCritChance = monster.critChance;
        monsterCritMultiplier = monster.critMultiplier;
        
        isPlayerInCombat = true;
        
        // 计算玩家攻击（使用新的圆桌系统）
        DEBUG_LOG("准备计算玩家攻击");
        playerAttackResult = player.gameData.performAttack(monster);
        
        if (playerAttackResult.hit) {
            // 攻击命中，造成伤害
            actualDamage = monster.takeDamage(playerAttackResult.damage);
            playerAttackHit = true;
            DEBUG_LOG(QString("玩家攻击命中 - 预期伤害:%1, 实际伤害:%2, 暴击:%3, 怪物剩余血量:%4")
                      .arg(playerAttackResult.damage).arg(actualDamage).arg(playerAttackResult.critical).arg(monster.health));
        } else {
            // 攻击未命中
            DEBUG_LOG("玩家攻击未命中/被闪避");
            playerAttackHit = false;
        }
        
        // 更新怪物状态
        monsterHealth = monster.health;
        isMonsterAlive = monster.isAlive();
        
    } // 锁在这里自动释放
    
    DEBUG_LOG("互斥锁已释放，开始发送战斗消息");
    
    // 使用成员变量而不是静态变量（线程安全）
    if (!m_roundCounters.contains(playerId)) {
        m_roundCounters[playerId] = 1;
    } else {
        m_roundCounters[playerId]++;
    }
    
    int currentRound = m_roundCounters[playerId];
    
    DEBUG_LOG(QString("*** 第%1回合战斗: 玩家 %2 VS %3").arg(currentRound).arg(playerName).arg(monsterName));
    
    // 现在可以安全地发送消息，因为锁已经释放
    DEBUG_LOG("准备发送回合开始消息");
    sendCombatMessage(playerId, QString(""));
    DEBUG_LOG("已发送空行");
    sendCombatMessage(playerId, QString("🔸 第 %1 回合开始").arg(currentRound));
    DEBUG_LOG("已发送回合开始消息");
    sendCombatMessage(playerId, QString("-------------------------------------------"));
    DEBUG_LOG("已发送分隔线");
    
    // 构建攻击消息（基于之前计算的结果）
    QString combatMsg;
    if (playerAttackHit) {
        combatMsg = playerAttackResult.message;
        // 添加伤害和防御信息
        if (actualDamage > 0) {
            if (monsterDefense > 0 && actualDamage < playerAttackResult.damage) {
                combatMsg += QString("，造成 %1 点伤害（被防御减少 %2 点）").arg(actualDamage).arg(playerAttackResult.damage - actualDamage);
            } else {
                combatMsg += QString("，造成 %1 点伤害").arg(actualDamage);
            }
        }
    } else {
        combatMsg = playerAttackResult.message;
    }
    
    DEBUG_LOG("准备发送玩家攻击消息");
    sendCombatMessage(playerId, combatMsg);
    DEBUG_LOG("玩家攻击消息已发送");
    
    if (isMonsterAlive) 
    {
        DEBUG_LOG("怪物还活着，准备发送怪物血量信息");
        sendCombatMessage(playerId, QString("💀 %1 剩余血量: %2/%3").arg(monsterName).arg(monsterHealth).arg(monsterMaxHealth));
        DEBUG_LOG("怪物血量信息已发送");
        
        // 🔥 实时更新：发送游戏状态数据包，让客户端状态面板实时更新
        DEBUG_LOG("发送GAME_STATUS数据包更新客户端状态面板");
        sendGameStatus(playerId);
        DEBUG_LOG("GAME_STATUS数据包已发送");
        
        // 怪物反击延迟1.5秒
        sendCombatMessage(playerId, "💭 怪物正在准备反击...");
        
        DEBUG_LOG("怪物还活着，准备设置反击定时器");
        
        QTimer::singleShot(1500, [this, playerId, currentRound, monsterName, monsterAttack, monsterDefense, monsterCritChance, monsterCritMultiplier]() {
            DEBUG_LOG("开始处理怪物反击");
            QMutexLocker counterLocker(&m_playersMutex);
            if (!m_players.contains(playerId) || !m_players[playerId].gameData.isInAutoCombat) 
            {
                DEBUG_LOG("怪物反击时玩家状态异常");
                return;
            }
            
            PlayerInfo& player = m_players[playerId];
            MonsterData& monster = player.currentMonster;
            
            DEBUG_LOG("怪物使用圆桌攻击系统攻击玩家");
            
            // 怪物使用新的圆桌攻击系统
            MonsterData::AttackResult monsterAttack = monster.performAttack(player.gameData);
            
            // 获取更新后的玩家状态
            bool playerStillAlive = player.gameData.isAlive();
            quint32 playerCurrentHealth = player.gameData.health;
            quint32 playerMaxHealth = player.gameData.maxHealth;
            quint32 playerDefense = player.gameData.defense;
            quint32 actualMonsterDamage = 0;
            
            QString counterMsg;
            if (monsterAttack.hit) {
                // 怪物攻击命中
                actualMonsterDamage = player.gameData.takeDamage(monsterAttack.damage);
                
                // 更新玩家状态
                playerStillAlive = player.gameData.isAlive();
                playerCurrentHealth = player.gameData.health;
                
                counterMsg = monsterAttack.message;
                
                // 添加伤害和防御信息
                if (actualMonsterDamage > 0) {
                    if (playerDefense > 0 && actualMonsterDamage < monsterAttack.damage) {
                        counterMsg += QString("，造成 %1 点伤害（你的防御减少了 %2 点伤害）").arg(actualMonsterDamage).arg(monsterAttack.damage - actualMonsterDamage);
                    } else {
                        counterMsg += QString("，造成 %1 点伤害").arg(actualMonsterDamage);
                    }
                }
            } else {
                // 怪物攻击未命中
                counterMsg = monsterAttack.message;
            }
            
            counterLocker.unlock();
            
            // 发送怪物反击消息
            sendCombatMessage(playerId, counterMsg);
            sendCombatMessage(playerId, QString("❤️ 你的血量: %1/%2").arg(playerCurrentHealth).arg(playerMaxHealth));
            
            // 🔥 实时更新：怪物反击后发送游戏状态数据包，让客户端状态面板实时更新
            DEBUG_LOG("怪物反击后发送GAME_STATUS数据包更新客户端状态面板");
            sendGameStatus(playerId);
            DEBUG_LOG("怪物反击后GAME_STATUS数据包已发送");
            
            if (!playerStillAlive) 
            {
                DEBUG_LOG("玩家死亡，游戏结束");
                // 玩家死亡
                sendCombatMessage(playerId, QString(""));
                sendCombatMessage(playerId, QString("💀 你被 %1 击败了！").arg(monsterName));
                sendCombatMessage(playerId, QString("💀 ======================================="));
                sendCombatMessage(playerId, QString("💀 游戏结束！你英勇战死"));
                sendCombatMessage(playerId, QString("💀 ======================================="));
                sendCombatMessage(playerId, QString("🔄 游戏数据已重置"));
                sendCombatMessage(playerId, QString("💡 点击 '🎮 开始游戏' 按钮重新挑战！"));
                sendCombatMessage(playerId, QString(""));
                
                DEBUG_LOG("准备停止自动战斗");
                stopAutoCombat(playerId);
                
                // 重置玩家状态
                QMutexLocker resetLocker(&m_playersMutex);
                if (m_players.contains(playerId)) {
                    PlayerInfo& deadPlayer = m_players[playerId];
                    deadPlayer.gameData = PlayerGameData(); // 重置为默认状态
                    deadPlayer.gameData.gameState = GameState::WAITING;
                    deadPlayer.currentMonster = MonsterData(); // 也要重置怪物数据
                    m_roundCounters.remove(playerId);
                    
                    DEBUG_LOG("玩家死亡，发送GAME_STATUS数据包更新客户端状态");
                    resetLocker.unlock();
                    
                    // 🔥 关键修复：发送游戏状态数据包给客户端，让客户端正确重置界面
                    sendGameStatus(playerId);
                    DEBUG_LOG("玩家死亡后GAME_STATUS数据包已发送");
                }
                return;
            }
            
            // 继续下一回合
            QTimer::singleShot(2000, [this, playerId]() {
                processCombatRound(playerId);
            });
        });
    }
    else 
    {
        // 怪物死亡，玩家获胜
        DEBUG_LOG("怪物死亡，玩家获胜");
        sendCombatMessage(playerId, QString(""));
        sendCombatMessage(playerId, QString("🎉 你击败了 %1！").arg(monsterName));
        sendCombatMessage(playerId, QString("⚔️ 胜利！战斗结束"));
        
        // 🔥 实时更新：怪物死亡后立即发送游戏状态数据包，让客户端显示怪物死亡状态
        DEBUG_LOG("怪物死亡，发送GAME_STATUS数据包更新客户端状态面板");
        sendGameStatus(playerId);
        DEBUG_LOG("怪物死亡GAME_STATUS数据包已发送");
        
        DEBUG_LOG("准备停止自动战斗");
        stopAutoCombat(playerId);
        m_roundCounters.remove(playerId);
        
        DEBUG_LOG("准备升级玩家并给予随机奖励");
        // 升级玩家并获取随机奖励
        QMutexLocker winLocker(&m_playersMutex);
        if (m_players.contains(playerId)) {
            PlayerInfo& winner = m_players[playerId];
            
            // 调用新的30关结构化升级系统，获取随机奖励消息
            QString rewardMessage = winner.gameData.levelUp();
            
            // 获取升级后的数据
            PlayerGameData newPlayerData = winner.gameData;
            QString playerName = winner.playerName;
            bool gameCompleted = (newPlayerData.level > 30); // 检查是否完成游戏
            winLocker.unlock();
            
            // 显示随机奖励结果
            sendCombatMessage(playerId, QString(""));
            sendCombatMessage(playerId, QString("==========================================="));
            sendCombatMessage(playerId, rewardMessage);
            sendCombatMessage(playerId, QString("==========================================="));
            
            // 检查游戏是否完成（30关胜利）
            if (gameCompleted) {
                // 游戏完成，显示胜利信息并准备重启
                DEBUG_LOG("游戏完成，30关全部通关");
                
                sendCombatMessage(playerId, QString(""));
                sendCombatMessage(playerId, QString("🎊 ======================================="));
                sendCombatMessage(playerId, QString("🏆 恭喜！您已成功完成全部30关挑战！"));
                sendCombatMessage(playerId, QString("👑 您是真正的冒险大师！"));
                sendCombatMessage(playerId, QString("⭐ 最终战绩:"));
                sendCombatMessage(playerId, QString("   🎯 通关等级: 30"));
                sendCombatMessage(playerId, QString("   ❤️ 最终血量: %1/%2").arg(newPlayerData.health).arg(newPlayerData.maxHealth));
                sendCombatMessage(playerId, QString("   ⚔️ 最终攻击力: %1").arg(newPlayerData.attackPower));
                sendCombatMessage(playerId, QString("   🏆 总击杀数: %1").arg(newPlayerData.totalKills));
                sendCombatMessage(playerId, QString("🎊 ======================================="));
                sendCombatMessage(playerId, QString(""));
                sendCombatMessage(playerId, QString("⏰ 游戏将在10秒后重新开始..."));
                sendCombatMessage(playerId, QString("🔄 准备迎接新的挑战！"));
                
                // 发送游戏完成的升级数据包给客户端
                QString completionMsg = QString("🎊 游戏完成！30关全部通关！您是真正的冒险大师！");
                auto levelUpPacket = std::make_shared<LevelUpPacket>(playerId, newPlayerData, completionMsg);
                sendToPlayer(playerId, levelUpPacket);
                
                DEBUG_LOG("准备10秒后重启游戏");
                // 10秒后重新开始游戏
                QTimer::singleShot(10000, [this, playerId]() {
                    DEBUG_LOG("执行游戏重启");
                    
                    // 重置玩家数据
                    QMutexLocker restartLocker(&m_playersMutex);
                    if (m_players.contains(playerId)) {
                        PlayerInfo& restartPlayer = m_players[playerId];
                        restartPlayer.gameData = PlayerGameData(); // 重置为初始状态
                        restartPlayer.gameData.gameState = GameState::WAITING;
                        restartLocker.unlock();
                        
                        // 显示重新开始消息
                        sendCombatMessage(playerId, QString(""));
                        sendCombatMessage(playerId, QString("🔄 ======================================="));
                        sendCombatMessage(playerId, QString("🆕 游戏重新开始！"));
                        sendCombatMessage(playerId, QString("🌟 欢迎再次挑战30关冒险！"));
                        sendCombatMessage(playerId, QString("🔄 ======================================="));
                        sendCombatMessage(playerId, QString(""));
                        sendCombatMessage(playerId, QString("💡 输入 /start 开始新的冒险旅程！"));
                        
                        // 发送重置后的状态给客户端
                        PlayerGameData resetData = restartPlayer.gameData;
                        QString restartMsg = QString("🆕 游戏重新开始！欢迎再次挑战30关冒险！");
                        auto restartPacket = std::make_shared<LevelUpPacket>(playerId, resetData, restartMsg);
                        sendToPlayer(playerId, restartPacket);
                    }
                });
                
                return; // 游戏完成，不继续后续流程
            }
            
            // 正常关卡完成，显示当前状态
            sendCombatMessage(playerId, QString("📊 当前状态:"));
            sendCombatMessage(playerId, QString("   🎯 等级: %1").arg(newPlayerData.level));
            sendCombatMessage(playerId, QString("   ❤️ 血量: %1/%2").arg(newPlayerData.health).arg(newPlayerData.maxHealth));
            sendCombatMessage(playerId, QString("   ⚔️ 攻击力: %1").arg(newPlayerData.attackPower));
            sendCombatMessage(playerId, QString("   🏆 总击杀: %1").arg(newPlayerData.totalKills));
            
            // 发送传统的升级数据包给客户端（保持兼容性）
            QString levelUpMsg = QString("🎯 第%1关完成！%2").arg(newPlayerData.level - 1).arg(rewardMessage);
            auto levelUpPacket = std::make_shared<LevelUpPacket>(playerId, newPlayerData, levelUpMsg);
            sendToPlayer(playerId, levelUpPacket);
            
            sendCombatMessage(playerId, QString(""));
            
            // 根据关卡类型显示不同的进入下一关提示
            if (newPlayerData.level == 10 || newPlayerData.level == 20 || newPlayerData.level == 30) {
                sendCombatMessage(playerId, QString("⚡ 即将面对Boss关卡，做好准备！"));
                sendCombatMessage(playerId, QString("⏳ 3秒后开始Boss战..."));
            } else {
                sendCombatMessage(playerId, QString("⏳ 3秒后开始下一关..."));
            }
            
            // 🔒 设置玩家状态为准备中，并发送状态更新
            {
                QMutexLocker prepareLocker(&m_playersMutex);
                if (m_players.contains(playerId)) {
                    m_players[playerId].gameData.gameState = GameState::PREPARING;
                    DEBUG_LOG("设置玩家状态为PREPARING");
                    
                    // 发送准备状态给客户端
                    auto preparePacket = std::make_shared<GameStatusPacket>(playerId, 
                                                                          m_players[playerId].gameData, 
                                                                          m_players[playerId].currentMonster, 
                                                                          "⏳ 准备下一关中...");
                    prepareLocker.unlock();
                    sendToPlayer(playerId, preparePacket);
                }
            }
            
            DEBUG_LOG("准备开始下一关");
            // 延迟开始下一关
            QTimer::singleShot(3000, [this, playerId]() {
                startNewGame(playerId);
            });
        }
    }
    
    DEBUG_LOG("=== processCombatRound完成 ===");
}

void GameServer::sendCombatMessage(quint32 playerId, const QString& message) 
{
    DEBUG_LOG(QString("[战斗消息] 发送给玩家%1: %2").arg(playerId).arg(message.isEmpty() ? "[空行]" : message));
    
    DEBUG_LOG("开始创建CombatMessagePacket");
    auto combatPacket = std::make_shared<CombatMessagePacket>(playerId, message);
    DEBUG_LOG("CombatMessagePacket创建完成");
    
    DEBUG_LOG("准备调用sendToPlayer");
    sendToPlayer(playerId, combatPacket);
    DEBUG_LOG("sendToPlayer调用完成");
    
    DEBUG_LOG("准备执行msleep");
    // 减少延迟，只保留必要的处理时间
    QThread::msleep(10);
    DEBUG_LOG("msleep执行完成");
}

QTimer* GameServer::getCombatTimer(quint32 playerId) 
{
    QMutexLocker locker(&m_timersMutex);
    
    if (!m_combatTimers.contains(playerId)) 
    {
        QTimer* timer = new QTimer(this);
        timer->setSingleShot(false);
        
        connect(timer, &QTimer::timeout, [this, playerId]() {
            processCombatRound(playerId);
        });
        
        m_combatTimers[playerId] = timer;
    }
    
    return m_combatTimers[playerId];
}

// ========== 新增：通用协议支持 ==========

void GameServer::onUniversalMessageProcessed(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    if (!message) 
    {
        return;
    }
    
    qDebug() << QString("收到通用协议消息: %1 (ID:%2)").arg(static_cast<int>(message->type)).arg(message->playerId);
    
    // 根据消息类型分发处理
    switch (message->type) 
    {
        case UniversalProtocol::MessageType::PROTOCOL_HANDSHAKE:
            handleProtocolHandshake(message, sender, port);
            break;
        case UniversalProtocol::MessageType::PLAYER_JOIN:
            handleUniversalPlayerJoin(message, sender, port);
            break;
        case UniversalProtocol::MessageType::PLAYER_LEAVE:
            handleUniversalPlayerLeave(message, sender, port);
            break;
        case UniversalProtocol::MessageType::GAME_START:
            handleUniversalGameStart(message, sender, port);
            break;
        case UniversalProtocol::MessageType::ATTACK:
            handleUniversalAttack(message, sender, port);
            break;
        default:
            qDebug() << "未处理的通用协议消息类型:" << static_cast<int>(message->type);
            break;
    }
}

void GameServer::handleProtocolHandshake(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    auto handshakeMsg = std::static_pointer_cast<UniversalProtocol::HandshakeMessage>(message);
    
    qDebug() << QString("=== 协议握手 ===");
    qDebug() << QString("客户端类型: %1").arg(static_cast<int>(handshakeMsg->clientInfo.clientType));
    qDebug() << QString("客户端名称: %1").arg(QString::fromStdString(handshakeMsg->clientInfo.clientName));
    qDebug() << QString("客户端版本: %1").arg(QString::fromStdString(handshakeMsg->clientInfo.clientVersion));
    qDebug() << QString("协议版本: %1").arg(QString::fromStdString(handshakeMsg->clientInfo.protocolVersion.toString()));
    
    // 检查协议兼容性
    UniversalProtocol::ProtocolVersion serverVersion{1, 0, 0};
    bool compatible = UniversalProtocol::MessageFactory::isProtocolCompatible(handshakeMsg->clientInfo.protocolVersion, serverVersion);
    
    if (compatible) 
    {
        qDebug() << "协议兼容性检查通过";
        
        // 为客户端分配玩家ID
        quint32 playerId = generatePlayerId();
        
        // 记录客户端类型
        {
            QMutexLocker locker(&m_clientTypesMutex);
            QString clientKey = QString("%1:%2").arg(sender.toString()).arg(port);
            m_clientTypes[playerId] = handshakeMsg->clientInfo.clientType;
            m_addressToClientType[clientKey] = handshakeMsg->clientInfo.clientType;
        }
        
        // 创建响应握手消息
        auto responseHandshake = std::make_shared<UniversalProtocol::HandshakeMessage>();
        responseHandshake->playerId = playerId;
        responseHandshake->timestamp = QDateTime::currentMSecsSinceEpoch();
        responseHandshake->clientInfo.clientType = UniversalProtocol::ClientType::QT_NATIVE;
        responseHandshake->clientInfo.clientName = "MUD Game Server";
        responseHandshake->clientInfo.clientVersion = "1.0.0";
        responseHandshake->clientInfo.protocolVersion = serverVersion;
        responseHandshake->clientInfo.supportedFeatures = {"combat", "levelup", "status", "chat"};
        
        sendUniversalMessage(playerId, responseHandshake);
        
        qDebug() << QString("已向客户端分配玩家ID: %1").arg(playerId);
    } 
    else 
    {
        qWarning() << "协议版本不兼容";
        
        // 发送错误响应
        auto errorMsg = std::make_shared<UniversalProtocol::ErrorMessage>();
        errorMsg->errorCode = 1001;
        errorMsg->errorDescription = "Protocol version incompatible";
        errorMsg->originalMessageId = message->messageId;
        
        sendRawUniversalData(ProtocolAdapters::getGlobalAdapterManager().getAdapter(UniversalProtocol::ClientType::JAVASCRIPT)->serializeMessage(*errorMsg), sender, port);
    }
}

void GameServer::handleUniversalPlayerJoin(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    auto joinMsg = std::static_pointer_cast<UniversalProtocol::PlayerJoinMessage>(message);
    
    // 如果没有玩家ID，检查是否为旧客户端（向后兼容）
    if (message->playerId == 0) 
    {
        // 检查客户端类型，如果是旧的Qt客户端，进行隐式握手
        QString clientKey = QString("%1:%2").arg(sender.toString()).arg(port);
        
        QMutexLocker clientTypesLocker(&m_clientTypesMutex);
        auto clientTypeIt = m_addressToClientType.find(clientKey);
        
        // 如果客户端类型未知或者是Qt原生客户端，进行隐式握手
        if (clientTypeIt == m_addressToClientType.end() || clientTypeIt.value() == UniversalProtocol::ClientType::QT_NATIVE)
        {
            qDebug() << "检测到旧版Qt客户端，执行隐式握手";
            
            // 为旧客户端分配playerId并注册
            UniversalProtocol::PlayerId newPlayerId = m_nextPlayerId++;
            m_addressToClientType[clientKey] = UniversalProtocol::ClientType::QT_NATIVE;
            m_clientTypes[newPlayerId] = UniversalProtocol::ClientType::QT_NATIVE;
            clientTypesLocker.unlock();
            
            // 更新消息的playerId
            message->playerId = newPlayerId;
            joinMsg->playerId = newPlayerId;
            
            qDebug() << QString("=== 旧版客户端隐式握手成功 ===");
            qDebug() << QString("分配玩家ID: %1").arg(newPlayerId);
            qDebug() << QString("客户端类型: Qt Native");
            qDebug() << QString("来源地址: %1:%2").arg(sender.toString()).arg(port);
        }
        else
        {
            // 新客户端必须明确握手
            qDebug() << "新版客户端未进行握手，要求先握手";
            
            auto errorMsg = std::make_shared<UniversalProtocol::ErrorMessage>();
            errorMsg->errorCode = 1002;
            errorMsg->errorDescription = "Handshake required before joining";
            errorMsg->originalMessageId = message->messageId;
            
            sendRawUniversalData(ProtocolAdapters::getGlobalAdapterManager().getAdapter(UniversalProtocol::ClientType::JAVASCRIPT)->serializeMessage(*errorMsg), sender, port);
            return;
        }
    }
    
    QString playerName = joinMsg->playerName.empty() ? QString("勇士_%1").arg(message->playerId) : QString::fromStdString(joinMsg->playerName);
    
    qDebug() << QString("=== 通用协议玩家加入 ===");
    qDebug() << QString("玩家ID: %1").arg(message->playerId);
    qDebug() << QString("玩家名称: %1").arg(playerName);
    qDebug() << QString("来源地址: %1:%2").arg(sender.toString()).arg(port);
    
    addPlayer(message->playerId, playerName, sender, port);
    
    // 发送加入确认
    auto response = std::make_shared<UniversalProtocol::PlayerJoinMessage>();
    response->playerId = message->playerId;
    response->timestamp = QDateTime::currentMSecsSinceEpoch();
    response->playerName = playerName.toStdString();
    
    sendUniversalMessage(message->playerId, response);
    
    qDebug() << QString("已向玩家 %1 发送加入确认").arg(playerName);
    
    // 发送欢迎信息（使用通用协议）
    QTimer::singleShot(500, [this, message, playerName]() {
        sendUniversalCombatMessage(message->playerId, "");
        sendUniversalCombatMessage(message->playerId, "🎉🎉🎉 欢迎来到MUD冒险世界！ 🎉🎉🎉");
        sendUniversalCombatMessage(message->playerId, "===========================================");
        sendUniversalCombatMessage(message->playerId, QString("👋 你好，%1！").arg(playerName).toStdString());
        sendUniversalCombatMessage(message->playerId, "");
        sendUniversalCombatMessage(message->playerId, "👤 【你的初始属性】");
        sendUniversalCombatMessage(message->playerId, "   💪 等级: 1");
        sendUniversalCombatMessage(message->playerId, "   ❤️  血量: 100/100");
        sendUniversalCombatMessage(message->playerId, "   ⚔️  攻击力: 1");
        sendUniversalCombatMessage(message->playerId, "   🏆 总击杀: 0");
        sendUniversalCombatMessage(message->playerId, "");
        sendUniversalCombatMessage(message->playerId, "🎯 【游戏说明】");
        sendUniversalCombatMessage(message->playerId, "   • 发送 START 消息开始第一关冒险");
        sendUniversalCombatMessage(message->playerId, "   • 发送 ATTACK 消息开始自动战斗");
        sendUniversalCombatMessage(message->playerId, "   • 发送 STATUS 消息查看详细状态");
        sendUniversalCombatMessage(message->playerId, "");
        sendUniversalCombatMessage(message->playerId, "💡 准备好了吗？发送 START 消息开始你的冒险之旅！");
        sendUniversalCombatMessage(message->playerId, "===========================================");
    });
}

void GameServer::handleUniversalPlayerLeave(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    qDebug() << QString(">>> 收到通用协议主动离开指令 - 玩家ID: %1").arg(message->playerId);
    
    QMutexLocker locker(&m_playersMutex);
    if (m_players.contains(message->playerId)) 
    {
        QString playerName = m_players[message->playerId].playerName;
        qDebug() << QString("    玩家: %1 主动请求离开游戏").arg(playerName);
        locker.unlock();
        
        removePlayer(message->playerId, true);
        
        // 清理客户端类型记录
        {
            QMutexLocker typeLocker(&m_clientTypesMutex);
            m_clientTypes.remove(message->playerId);
        }
        
        // 发送离开确认
        auto response = std::make_shared<UniversalProtocol::PlayerJoinMessage>();
        response->type = UniversalProtocol::MessageType::PLAYER_LEAVE;
        response->playerId = message->playerId;
        response->timestamp = QDateTime::currentMSecsSinceEpoch();
        
        sendUniversalMessage(message->playerId, response);
        
        qDebug() << QString("已确认玩家 %1 的离开请求").arg(playerName);
    }
}

void GameServer::handleUniversalGameStart(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    // 复用现有的游戏开始逻辑，创建临时的Qt数据包
    auto qtPacket = std::make_shared<GamePacket>(PacketType::GAME_START, message->playerId);
    qtPacket->timestamp = message->timestamp;
    
    handleGameStart(qtPacket, sender, port);
}

void GameServer::handleUniversalAttack(std::shared_ptr<UniversalProtocol::UniversalMessage> message, const QHostAddress& sender, quint16 port) 
{
    // 复用现有的攻击逻辑，创建临时的Qt数据包
    auto qtPacket = std::make_shared<GamePacket>(PacketType::ATTACK, message->playerId);
    qtPacket->timestamp = message->timestamp;
    
    handleAttack(qtPacket, sender, port);
}

void GameServer::sendUniversalMessage(quint32 playerId, std::shared_ptr<UniversalProtocol::UniversalMessage> message) 
{
    QMutexLocker locker(&m_playersMutex);
    if (!m_players.contains(playerId)) 
    {
        return;
    }
    
    const auto& player = m_players[playerId];
    QHostAddress target = player.address;
    quint16 port = player.port;
    locker.unlock();
    
    // 获取客户端类型
    UniversalProtocol::ClientType clientType = UniversalProtocol::ClientType::QT_NATIVE;
    {
        QMutexLocker typeLocker(&m_clientTypesMutex);
        if (m_clientTypes.contains(playerId)) 
        {
            clientType = m_clientTypes[playerId];
        }
    }
    
    // 根据客户端类型选择适配器
    auto& adapterManager = ProtocolAdapters::getGlobalAdapterManager();
    auto adapter = adapterManager.getAdapter(clientType);
    
    if (adapter) 
    {
        message->timestamp = message->timestamp > 0 ? message->timestamp : QDateTime::currentMSecsSinceEpoch();
        auto data = adapter->serializeMessage(*message);
        sendRawUniversalData(data, target, port);
    } 
    else 
    {
        qWarning() << QString("找不到适配器，客户端类型: %1").arg(static_cast<int>(clientType));
    }
}

void GameServer::sendRawUniversalData(const std::vector<uint8_t>& data, const QHostAddress& target, quint16 port) 
{
    if (m_receiver) 
    {
        QByteArray qtData(reinterpret_cast<const char*>(data.data()), static_cast<int>(data.size()));
        m_receiver->writeDatagram(qtData, target, port);
    }
}

void GameServer::sendUniversalCombatMessage(quint32 playerId, const std::string& message) 
{
    auto combatMsg = std::make_shared<UniversalProtocol::CombatMessage>();
    combatMsg->playerId = playerId;
    combatMsg->message = message;
    combatMsg->timestamp = QDateTime::currentMSecsSinceEpoch();
    
    sendUniversalMessage(playerId, combatMsg);
    
    // 短暂延迟以避免消息过快
    QThread::msleep(10);
}